package stone926.mods.more_enchantments.enchantments;

import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.EnchantmentTarget;
import net.minecraft.entity.EquipmentSlot;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.projectile.WitherSkullEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.World;
import stone926.mods.more_enchantments.MoreEnchantmentsMod;
import stone926.mods.more_enchantments.interfaces.IWitherSkull;

import java.util.Random;

/**
 * 荆棘自爆：受到致命伤害后自爆
 * 凋零剑：扩展到药水效果剑
 */
public class WitherSkullShooterEnchantment extends Enchantment {

  public WitherSkullShooterEnchantment() {
    super(Enchantment.Rarity.COMMON, EnchantmentTarget.BOW, new EquipmentSlot[]{EquipmentSlot.MAINHAND});
  }

  public static double getExtraChargedProbability(int level) {
    return 0.2 * level;
  }

  public static float getExtraModifierZ(int lvl, float pullProgress) {
    return lvl * 0.11F + 0.8F * pullProgress;
  }

  public static float getExtraDamage(int lvl, float f) {
    return lvl + f * 12;
  }

  public static WitherSkullEntity getWitherSkull(int lvl, LivingEntity user, World world, float pullProgress, int flashLvl) {
    float f1 = -MathHelper.sin(user.getYaw() * 0.017453292F) * MathHelper.cos(user.getPitch() * 0.017453292F);
    float f2 = -MathHelper.sin((user.getPitch() + user.getRoll()) * 0.017453292F);
    float f3 = MathHelper.cos(user.getYaw() * 0.017453292F) * MathHelper.cos(user.getPitch() * 0.017453292F);
    WitherSkullEntity skull = new WitherSkullEntity(world, user, f1, f2, f3);
    skull.setPos(
      skull.getX(), skull.getY() + user.getEyeHeight(user.getPose()) - skull.getEyeHeight(skull.getPose()),
      skull.getZ()
    );
    boolean isCharged = false;
    float modifierZ = 1F + getExtraModifierZ(lvl, pullProgress) + flashLvl * 0.14F;
    if (new Random().nextDouble() <= Math.min(1, 0.4 + getExtraChargedProbability(lvl))) {
      skull.setCharged(true);
      isCharged = true;
    }
    if (isCharged) {
      skull.setVelocity(
        user, user.getPitch(), user.getYaw(), 0.0F, modifierZ, -1 * pullProgress + 1
      );
    } else {
      skull.setVelocity(
        user, user.getPitch(), user.getYaw(), 0.0F,
        modifierZ * 0.63F, -1 * pullProgress + 1
      );
    }
    skull.setOwner(user);
    ((IWitherSkull) skull).setDrag(0.96F);
    ((IWitherSkull) skull).setExtraDamage(getExtraDamage(lvl, pullProgress));
    return skull;
  }

  @Override
  public boolean isAcceptableItem(ItemStack stack) {
    return stack.isOf(MoreEnchantmentsMod.WITHER_SKULL_BOW);
  }

  public int getMinPower(int level) {
    return 1 + (level - 1) * 10;
  }

  public int getMaxLevel() {
    return 3;
  }

  @Override
  protected boolean canAccept(Enchantment other) {
    return super.canAccept(other) && other != MoreEnchantmentsMod.RANDOM_FIREBALL_SHOOTER && other != MoreEnchantmentsMod.SHULKER_BULLET_SHOOTER;
  }

}

